package com.core.utils;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

import com.core.managers.SessionManager;


public class LocalizableString {

	private static LocalizableString instance;
	private Locale                   currentLocale;
	private ResourceBundle           currentBundle;



	public static Locale localeFromString ( String localeString ) {

		if ( localeString == null ) {
			return Locale.getDefault();
		}
		localeString = localeString.trim();
		if ( localeString.toLowerCase().equals("default") ) {
			return Locale.getDefault();
		}

		// Extract language
		int languageIndex = localeString.indexOf('_');
		String language = null;
		if ( languageIndex == -1 ) {
			// No further "_" so is "{language}" only
			return new Locale(localeString, "");
		} else {
			language = localeString.substring(0, languageIndex);
		}

		// Extract country
		int countryIndex = localeString.indexOf('_', languageIndex + 1);
		String country = null;
		if ( countryIndex == -1 ) {
			// No further "_" so is "{language}_{country}"
			country = localeString.substring(languageIndex + 1);
			return new Locale(language, country);
		} else {
			// Assume all remaining is the variant so is
			// "{language}_{country}_{variant}"
			country = localeString.substring(languageIndex + 1, countryIndex);
			String variant = localeString.substring(countryIndex + 1);
			return new Locale(language, country, variant);
		}
	}



	public static LocalizableString sharedInstance () {

		if ( instance == null ) {
			instance = new LocalizableString();
		}
		return instance;
	}



	public LocalizableString() {

	}



	private Locale findOrRecreateLocale ( String localeName ) {

		SessionManager sessionManager = SessionManager.sharedInstance();
		String localeStr = sessionManager.userLocale();
		if ( currentLocale == null ) {
			currentLocale = LocalizableString.localeFromString(localeStr);
		}
		return currentLocale;
	}



	public String localizable ( String identifier,
	                            String localeName ) {

		if ( currentBundle == null ) {
			Locale locale = this.findOrRecreateLocale(localeName);
			if ( locale == null ) {
				return identifier;
			}

			ResourceBundle.clearCache();
			Locale.setDefault(locale);

			try {
				currentBundle = PropertyResourceBundle.getBundle("Localization", locale);
			} catch ( Exception e ) {
				e.printStackTrace();
			}
			if ( currentBundle == null ) {
				return identifier;
			}
		}

		String result = null;
		try {
			result = currentBundle.getString(identifier);
		} catch ( MissingResourceException exception ) {
			result = identifier;
		}
		return result;
	}



	public String localizable ( String identifier ) {

		return this.localizable(identifier, null);
	}
}
